package utils

import (
	"strconv"
	"strings"
	"time"
	"unicode"
)

func LowerFirstLetter(s string) string {
	if s == "" {
		return s
	}
	runes := []rune(s)
	runes[0] = unicode.ToLower(runes[0])
	return string(runes)
}

type ParseFunc[T any] interface {
	Parse(string) (T, error)
}

// IntParser 实现 ParseFunc 接口，用于解析整数
type IntParser struct{}

func (p IntParser) Parse(s string) (int, error) {
	return strconv.Atoi(s)
}

// IntParser 实现 ParseFunc 接口，用于解析整数
type FloatParser struct{}

func (p FloatParser) Parse(s string) (float64, error) {
	return strconv.ParseFloat(s, 64)
}

// BoolParser 实现 ParseFunc 接口，用于解析布尔值
type BoolParser struct{}

func (p BoolParser) Parse(s string) (bool, error) {
	return strconv.ParseBool(s)
}

// TimeParser 实现 ParseFunc 接口，用于解析时间
type TimeParser struct {
	Layout string
}

func (p TimeParser) Parse(s string) (time.Time, error) {
	return time.Parse(p.Layout, s)
}

// StringToArray 将逗号分隔的字符串转换为泛型类型的数组
func StringToArray[T any](s string, parser ParseFunc[T]) ([]T, error) {
	strArray := strings.Split(s, ",")
	result := make([]T, 0, len(strArray))
	for _, str := range strArray {
		value, err := parser.Parse(strings.TrimSpace(str))
		if err != nil {
			return nil, err
		}
		result = append(result, value)
	}
	return result, nil
}
